package middle

import (
	"sync"
	"time"

	"test/lib/goframe/in"
)

var (
	defLimit = newLimit(20)
)

type Limit struct {
	runing chan byte    //正在执行的接口
	mu     sync.RWMutex //读写锁
	limit  int          //最大执行数量
}

func newLimit(limit int) *Limit {
	return &Limit{
		runing: make(chan byte, limit),
		limit:  limit,
	}
}

func (this *Limit) do() {
	select {
	case this.runing <- byte(0):
	default:
		in.Err("请求过于频繁,请稍后再试")
	}
}

func (this *Limit) done() {
	select {
	case <-this.runing:
	case <-time.After(time.Millisecond):
	}
}
